
Ext.util.Format.comboRenderer = function(combo) {
	if(combo instanceof Ext.form.ComboBox){
		return function(value) {
			var reg = /^\d+$/;
			if (!reg.test(value)) {
				return value;
			}
			var record = combo.findRecord(combo.valueField, value);
			return record
					? record.get(combo.displayField)
					: combo.valueNotFoundText;
		}
	}
}
Ext.util.Format.booleanRenderer = function(value, cellmeta, record, rowIndex, columnIndex, store){
		if (value===true || value>0) {
			return "是";
		}
		return "否";
}


	/* 获得按钮栏 */
	var initButtons = function(buttons, operation,container) {
		var btnToolbar = new Ext.Toolbar({
			border : false,
			frame : true,
			buttonAlign : 'center',
			itemId : 'btnPanel',				
			defaults : {width : 70,autoHeight : true}
	    });
		for (var i = 0; i < buttons.length; i++) {
			var obj = buttons[i];
			var btn = new Ext.Button({
				text : obj.value,
				tooltipType : 'title',
				tooltip : buttons[i].tips,
				url : obj.url,
				func : obj.func,
				handler : operation
			});
			btnToolbar.add(btn);
		}
		container.add(btnToolbar);
	    container.doLayout();
		return btnToolbar;
	}
	function removeButtons(formPanel) {
		var panel = formPanel.getComponent('btnPanel');
		if(panel)panel.destroy();
	}

	function getPartpropertyLookUp(url){
		var store=getStorePartproperty(url);
		return new Ext.form.Lookup({
	        store: store,
	        fieldLabel:'零件编码',
	        width:200,
	        displayField:'name',
	        lookupField:'code',
	        valueField:'code',
	        hiddenName:'code',
	        mode: 'local',
	        triggerAction: 'all',
	        emptyText:'编码/名字/拼音码',
	        selectOnFocus:true,
	        allowBlank:false,
	        blankText:'零件不能为空',
	        pageSize:20		        
		});
	}
	function getStorePartproperty(url){
		return new Ext.data.Store({
		   proxy: new Ext.data.HttpProxy({url:url}),
		   baseParams:{start:0,limit:20},
		   autoLoad:true,
		   reader : new Ext.data.JsonReader({
			   totalProperty: 'totalProperty',
			   root: 'root'
			   },	
		   	   [
				   {name:'id'},
				   {name:'name'},
				   {name:'code'}
			   ])
		});
    }
    function encodeFilte(o){
		if(Ext.isArray(o)){
			Ext.each(o,function(obj){
				obj=encodeFilte(obj);
			});
		}else{
			for(pro in o){
				if(!o[pro]){
				o[pro] = undefined;		
				}
			}
		}
		return o
	}
	/*改变window的uecId*/
	function changeWindowUecId(code,oldUecId,newUecId){
		var desktop =Uec3.App.getDesktop();  
		if(oldUecId){
			var win=desktop.getWindowByUecId(oldUecId);
			if(win)win.taskButton.setText(win.title+":"+code);
		}
		if(oldUecId&&newUecId)desktop.changeWindowUecId(oldUecId,newUecId);   
	}
	
	function getOwnerAjax(conf){
		var ajax=new Ext.data.Connection();
		var config={
	            title : "提示",
	            msg : "保存中,请稍后.....",
	            buttons: false,
	            closable:false,
	            width:200,
	            wait:true,
	            modal:true	            
		    };
		if(conf){
			config=Ext.applyIf(conf,config);
		}
	   	Ext.util.Observable.capture(ajax,function(e,conn,b,c){
			if(e=='beforerequest'){
				
				Ext.MessageBox.show(config);
			}else if(e=='requestcomplete'||e=='requestexception'){
				Ext.MessageBox.hide();
				if(e=='requestexception')Ext.Msg.alert("警告",'保存失败,网络延迟或断网,请稍后重写打开');
			}
		});
		return ajax;
	}
	function formBingingKeys(formPanel,window){
		var basicForm=formPanel.getForm();
		var delayMus=400;
		var fields=getkeyBingFields(formPanel,window);
		Ext.each(fields,function(field,index,fields){
			
			field.on('keypress',function(o,e){
				 if(o.xtype=="lookupBox2"){
	 				o.triggerBlur();
	 			 }

	 			 if(e.getKey()==e.TAB){
	 			 	e.stopEvent();
	 			 }
				 if (e.getKey() == e.ENTER||e.getKey()==e.TAB) {   
                      fields[index+1].focus(true,delayMus);
                }   
			});
		});
		window.on("show",function(){
			if(fields[0]){
				var firstField=basicForm.findField(fields[0].getName());
				if(firstField)firstField.focus(true,delayMus);
			}
		});
		
		/*var keyMap=new Ext.KeyMap(win.el,[{
	    key: [13], // 或者是 Ext.EventObject.ENTER
	    //stopEvent:true,
 		fn: function(){
 		 	var arr=getFieldIndex(fields);
 		 	var index=arr[0];
 		 	var curField=arr[1];
 		 	if(!curField){
 		 		return;
 		 	}
 		 	var next;
			if(index==fields.length-1){
				if(curField.handler){
					if(basicForm.isValid()){
						curField.handler();
					}else{
						basicForm.items.each(function(f){
							if(!f.isValid()){
								f.focus(true,delayMus);
								return false;
							}
						});
					}
					return;
				}else{
					next=fields[0];
				}
			}else{
 		 		next=fields[index+1];
			}
	 		curField.blur();
	 		curField.hasFocus=false;
	 		if(curField.xtype=="lookupBox2"){
	 			curField.triggerBlur();
	 		}
	 		next.focus(true,delayMus);
	 		//next.hasFocus=true
	 		//basicForm.findField(next.getName()).focus(true,delayMus);
 		}
    	}]);*/
 	  	/*keyMap.addBinding([{
		    key: 9,
			fn: module.getObjByKey("itemClose")
	    }
		]);*/
		/*keyMap.enable();
		basicForm.findField(fields[0].getName()).focus(true,delayMus);
		Ext.util.Observable.capture(win,function(e){
			if(e=='show'){
				keyMap.enable();
				basicForm.findField(fields[0].getName()).focus(true,delayMus);
			}else if(e=='hide'){
				keyMap.disable();
			}
		});*/
   		//return keyMap;
	}
	function getFieldIndex(fields){
    	var curField;
    	var index=Ext.each(fields,function(field){
 		 		if(field.hasFocus){
 		 			curField=field;
 		 			return false;
 		 		}
 		 		
 		 });
 		 if(!curField){
 		 	return [0,fields[0]];
 		 }
 		return [index,curField];
    }
   function getkeyBingFields(formPanel,window){
    	var fields=[];
    	Ext.each(formPanel.getForm().items.getRange(),function(item){
    		if(item.xtype!='hidden'&& !item.readOnly && !item.disabled){
    			fields.push(item);
    		}
    	});
    	/*fields.sort(function(a,b){
    		if(a['focusOrder']&&b['focusOrder']){
    			return a['focusOrder']>b['focusOrder']?1:-1;
    		}else if(a['focusOrder']){
    			return -1;
    		}else if(b['focusOrder']){
    			return 1;
    		}else{
    			return 0;
    		}
    	});  */
    	Ext.each(formPanel.buttons,function(button){
    		if(button.iconCls=='icon-save'){
    			fields.push(button);
    		}
    	});
    	if(window&&window.buttons){
	    	Ext.each(window.buttons,function(button){
	    		if(button.iconCls=='icon-save'){
	    			fields.push(button);
	    		}
	    	});  
    	}
 		return fields;
    }
    function winBingingKeys(win,objsMap){
    	 var grid=objsMap.get("itemGrid");
    	 var keyMap=new Ext.KeyMap(Ext.getBody(),[{
	     key: Ext.EventObject.PAGEDOWN, // 或者是 Ext.EventObject.ENTER
 		 fn: function(){
 		 	var pagingBar=grid.getBottomToolbar();
 		 	var pageData=pagingBar.getPageData();
			pagingBar.changePage(pageData.activePage+1);
 		 }
   		 },{
	     key: Ext.EventObject.PAGEUP, 
 		 fn: function(){
			var pagingBar=grid.getBottomToolbar();
 		 	var pageData=pagingBar.getPageData();
			pagingBar.changePage(pageData.activePage-1);
 		 }
    	}]);
    
    }
    
	function showMoney(v, meta, record){
        v = (Math.round((v-0)*100))/100;
        v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
        v = String(v);
        var ps = v.split('.'),
            whole = ps[0],
            sub = ps[1] ? '.'+ ps[1] : '.00',
            r = /(\d+)(\d{3})/;
        while (r.test(whole)) {
            whole = whole.replace(r, '$1' + ',' + '$2');
        }
        v = whole + sub;
        //v=whole;
        if(record.get("documentType") ==3){
            //return '-¥' + v.substr(1);
        	return '-' + v;
        }
        return "" +  v;
    }
	
	function revert(store,grid,record,id){
		   Ext.Ajax.request({
				url : Uec3.App.Constants.homeUrl+ '/partner/query_partner!revertPartner.do',
				success : function(res) {
					var result = Ext.decode(res.responseText);
					if (result.success == "OK"){
						if(grid){
							grid.loadMask.hide();
						}
						if(store&&record){
							store.remove(record);
							store.reload();
						}
						Ext.MessageBox.alert("提示","您已经成功恢复该往来单位信息")
					}
				},
				failure : function(res) {
					Ext.Msg.alert('失败', "网络出现异常，请重先连接");
				},
				params : {id : id}
			});
	}
	
	function checkCertify(store,grid,record,id,companyId,name,winId,text,isAlertOrder,func){
		var desktop = Uec3.App.getDesktop();
		Ext.Ajax.request({
			url : Uec3.App.Constants.homeUrl+ '/partner/query_partner!add_Partner.do',
			success : function(res) {
				var result = Ext.decode(res.responseText);
				if (result.success == "OK"){ 
					 if(result.reason=="you partner already delete you"){
						    Ext.Msg.confirm('提示', "该公司已经把你从他的往来单位中删除,是否重先发送加为往来单位邀请?",
									function(button) {
						if (button == 'yes') {
							desktop.launchWindowByParam("requestAddPartner",{companyId:companyId,name:name,winId:winId,text:text,partnerId:id,isAlertOrder:isAlertOrder});             
										}});
					 }else{
					     desktop.launchWindowByParam("requestAddPartner",{companyId : companyId,name:name,winId:winId,text:text,partnerId:id,isAlertOrder:isAlertOrder});
					 }
				} else {
					     if(result.failure=="you is success to revert"){
	                     		Ext.Msg.alert("提示","该公司是您的已删除往来单位,现已恢复该往来单位的信息,请您去往来单位列表查看",function(){									
		                     		if(store){
		                     		   store.reload();
		                     		}
								});  
					     }
                         if(result.failure=="isSelf"){
                     		Ext.Msg.alert("提示","您好,不能加自己为往来单位");                      	 
                         }
			            if(result.failure=="alreadyPartner"){
			            	if(isAlertOrder){
			            		func();			            		
			            	}else{
			            		Ext.Msg.alert("提示"," 您好,该公司已经是你的往来单位,不能重复增加,请到往来单位列表查看");   
			            	}
			           }
      		           if(result.failure=="you is Partner to relation"){
      		        	     revert(store,grid,record,id);
			           }
				}
			},

			failure : function(res) {

				Ext.Msg.alert('失败', "网络出现异常，请重先连接");

			},

			params : {
				companyId : companyId,partnerId:id
			}

		});
	}
	/**
	 * 按钮添加
	 * @author yi
	 * @param {} buttons
	 */
	function fillButtons(buttons,operation,parentCt) {
			var btnPanel = parentCt.getComponent("btnPanel");
			if (btnPanel) {
				btnPanel.destroy();
			}						
			var buttonBar = new Ext.Toolbar({
				border : false,
				frame : true,
				buttonAlign : 'center',
				itemId : 'btnPanel',				
				defaults : {
					//margins : '0 10',					
					width : 70,
					autoHeight : true
				}
		    });
			for (var i = 0; i < buttons.length; i++) {
				var btn = new Ext.Button({
							text : buttons[i].value,
							tooltipType : 'title',
							tooltip : buttons[i].tips,
							url:Uec3.App.Constants.homeUrl+buttons[i].url,
		                    func:buttons[i].func,
							handler : operation
				});							
				buttonBar.add(btn)
				buttonBar.doLayout();				
			}							
			parentCt.add(buttonBar);
			parentCt.doLayout();
		}
	
	function getPartnerLookupStore(relation){
		
		var partnerStore = new Ext.data.JsonStore({
			url : Uec3.App.Constants.homeUrl+ "/partner/query_partner!queryPartner.do",
			id : "id",
			root : 'root',
			totalProperty : 'totalProperty',
			remoteSort : true,
			baseParams : {start : 0,limit : 4,type : relation},
			fields : [
				{name : 'id',type : 'int'},
				{name : 'pyCode',type : 'string'},
				{name : 'name',type : 'string'},
				{name : 'companyId',type : 'int'}]
		});	
		
		return partnerStore;
	}
	/**
	 * 往来单位lookup组建
	 * @param {} relation,客户关系
	 * @param {} config,配置参数
	 * @return {}
	 */	
	function getPartnerLookup(relation,config){
		
		var partnerCombo = new Ext.form.LookupBox2({
			store: getPartnerLookupStore(relation),
 			fieldLabel : relation == 0 ? '客户':'供货单位',
 			//id:"partnerName",
	        displayField:'name',
	        lookupField:'pyCode',
	        valueField:'id',
	        hiddenId : relation == 0 ?'partnerIdBySeller_' + new Date().getTime():'partnerIdByBuyer_'+new Date().getTime(),
	        hiddenName : relation == 0 ?'partnerIdBySeller' : 'partnerIdByBuyer',
	        typeAhead: false,
	        mode: 'remote',
	        // tpl : '<tpl for="."><div ext:qtip="{pyCode}. {name}"
			// class="x-combo-list-item">{pyCode}. {name}</div></tpl>',
	        triggerAction: 'all',
	        emptyText:relation == 0 ? '选择客户...' : '选择供货商..',	       
	        selectOnFocus:true,
	        // applyTo: 'partner_lookup_combox',
	        queryParam:'queryParam',
	        queryDelay:10,
	        typeAheadDelay:10,
	        //lookupCallBackEvents:['lookupChange'],
	        pageSize:4,
	        start:0,
	        width:250,
	        anchor : '100%',
	        app:Uec3.App,
	        triggerTags : [{moduleId:'partner_query',triggerClass:'x-form-search-trigger',params:{partnerType:relation}},{moduleId:'partner_add'}],
	        cleanValueTrigger : {
	           	triggerHandler : function() {
					this.readyToClearValue();
		       	},
	       	triggerClass : 'x-form-clear-trigger'
			},
			onSelect : function(record, index) {
				if (this.fireEvent('beforeselect', this, record, index) !== false) {
					this.collapse();
					this.fireEvent('select', this, record, index);
				}
			}
		});
		if(!Ext.isEmpty(config)){
			Ext.apply(partnerCombo,config);
		}				
		return partnerCombo;
	}
	
	function getPartnerAddStore(){
		var partnerAddStore = new Ext.data.JsonStore({
			root:'root',
            fields: [
       		     {name:'areaId'},
				 {name:'province',type:'string'},
				 {name:'city',type:'string'}, 
				 {name:'district',type:'string'}, 
				 {name:'street',type:'string'},
                 {name:'postCode',type:'string'},	                 
				 {name:'receiverName',type:'string'},
				 {name:'phone',type:'string'},
				 {name:'mobile',type:'string'},
				 {name:'address',type:'string'}
       		]
		});
		
		return partnerAddStore;
	}
	/**
	 * 往来单位地址
	 * @param {} partnerLookup,往来单位lookup组件
	 */
	function getPartnerAddLookup(partnerLookup,config){
	
		var partnerAddLookup = new Ext.form.LookupBox2({
			store: getPartnerAddStore(),
 			fieldLabel:'退货地址',	  			
	        displayField:'address',
	        lookupField:'areaId',
	        valueField:'areaId',	        
	        typeAhead: false,
	        mode: 'local',
	        triggerAction: 'all',
	        name:'address',
	        emptyText:'选择退货地址..',	      
	        editable:false,	      
	        //width:666,
	        anchor : '100%',
	        app:Uec3.App,
            autoDestory:true,
            lookupCallBackEvents:['lookupChange'],
            triggerTags : [{moduleId:'partnerAddress_query',triggerClass:'x-form-search-trigger',params:{partnerCmb : partnerLookup}},{moduleId:'partnerAddress_add',params:{partnerCmb : partnerLookup}}]
		});
		
		if(!Ext.isEmpty(config)){
			Ext.apply(partnerAddLookup,config);
		}
		
		return partnerAddLookup;
	}
	
	function redirectUrl(id,params){
     	var desktop =Uec3.App.getDesktop();   
 		desktop.launchWindowByParam(id,params); 	 		
    }
    
    
    function getPartStoreComb4Grid(config){
		var store_ds = new Ext.data.JsonStore({
			url : Uec3.App.Constants.homeUrl+ '/store/base!query.do',
			root:'root',
			totalProperty: "totalProperty",
			fields:[
				{name : 'id',type:'int'},
				{name : 'name',type:'string'},
				{name : 'pyCode',type:'string'},
				{name : 'departmentName',type:'string'}
			]
		});
		var resultTpl = new Ext.XTemplate(
            '<tpl for="."><div class="search-item">',
               '{name},{departmentName}',             
            '</div></tpl>'
   		);
		var storeId_comboBox= new Ext.form.ComboBox({
			typeAhead: true,
			hiddenValue:'id',
			displayField : 'name',
			//hiddenId: 'storeName_'+new Date().getTime(),	 
			mode : 'remote',
			store : store_ds,
			tpl: resultTpl,
			itemSelector: 'div.search-item',
			selectOnFocus : true,
			forceSelection  :true,
			triggerAction : 'all',
			valueNotFoundText:'',
			loadingText : '加载中...',
			editable:false,
			pageSize:5,
			listWidth :220,
			emptyText : '请选择仓库...'
		}); 
		
		if(!Ext.isEmpty(config)){
			Ext.apply(storeId_comboBox,config);
		}
		
		return storeId_comboBox;
    }
    
    function getOrderIdLookup(dispalyField,config){
    	var availableOrder_store = new Ext.data.JsonStore({
			root : 'root',
			fields:['id',dispalyField]
		});    	
    	var orderIdComb = new Ext.form.LookupBox2({
    		store: availableOrder_store,	  			
			displayField:dispalyField,
			lookupField:'id',
			valueField:'id',
			hiddenId:'ordersId'+new Date().getTime(),
			hiddenName:'ordersId',
			typeAhead: false,
			// mode: 'remote',
			//tpl : '<tpl for="."><div ext:qtip="{pyCode}. {name}" class="x-combo-list-item">{pyCode}. {name}</div></tpl>',
			triggerAction: 'all',
			emptyText:'请选择订单号...',
			selectOnFocus:true,		        
			editable : false,		      
			app:Uec3.App,	
			lookupCallBackEvents:['lookupChange'],
			triggerTags : [],
			cleanValueTrigger : {
			    triggerHandler : function() {
					this.readyToClearValue();
			    },
			    triggerClass : 'x-form-clear-trigger'
			}
    	});
    	
    	if(!Ext.isEmpty(config)){
			Ext.apply(orderIdComb,config);
		}
    	return orderIdComb;
    }

    
Uec3.FieldFactory=Ext.extend(Ext.util.Observable,{
	constructor:function(){
		
	},
	getStoreCombo:function(config){
		var store_ds = new Ext.data.JsonStore({
			url : Uec3.App.Constants.homeUrl+ '/store/base!query.do',
			root:'root',
			totalProperty: "totalProperty",
			fields:[{name : 'id',type:'int'},{name : 'name',type:'string'},{name : 'pyCode',type:'string'}]
		});
		var defaultConfig={
			fieldLabel : '仓库',store: store_ds, displayField:'name',lookupField:'pyCode',valueField:'id',
	        editable:false,name:'storeId',hiddenName:'storeId',allowBlank:false,typeAhead: false,mode: 'remote',
	        triggerAction: 'all',emptyText:'请选择仓库...',selectOnFocus:true,queryDelay:10,typeAheadDelay:10,
	        pageSize:6,width:200,autoDestory:true,queryParam:'keyword',app:Uec3.App,
	     	triggerTags:[{moduleId: 'store_list',triggerClass:'x-form-search-trigger'},{moduleId: 'store_add'}]
		   };
		config=Ext.apply(defaultConfig,config||{});
		var combo=new Ext.form.LookupBox2(config);
		return combo;
	},
	getCodeCombo:function(config){
		var ds_code_select = new Ext.data.JsonStore({
			url:Uec3.App.Constants.homeUrl+"/part/queryPart!getPartByCodeImplicitExt.do",
		    root:'root',
		    totalProperty: "totalProperty", //总记录数
	        fields:[{name:'code',type:'string'}]
		});
		var defaultConfig={
		    xtype:'combo',width:200,allowBlank : false,blankText : '零件编码不能为空',name : 'code',
			valueField:'code',displayField : 'code',emptyText:'编码至少输入三位!',mode : 'remote',
			queryParam :'queryParam',queryDelay:500,minChars :3,pageSize:10,tpl: this.resultTpl,
			listWidth:251,itemSelector: 'div.x-combo-list-item',store : ds_code_select,selectOnFocus : true,
			triggerAction : 'all',loadingText : '加载中...'};
		config=Ext.apply(defaultConfig,config||{});
		var combo=new Ext.form.ComboBox(config);
		return combo;
	},
	
	getPartPropertyCodeCombo:function(config){
		var ds_code_select = new Ext.data.JsonStore({
			url:Uec3.App.Constants.homeUrl+"/part/getCodeByCompanyIdWithPage.do",		   
			root:'root',
		    totalProperty: "totalProperty", //总记录数
	        fields:[{name:'code',type:'string'}]
		});
		var defaultConfig={
		    xtype:'combo',width:200,name : 'code',valueField:'code',displayField : 'code',
		    emptyText:'请输入至少2位零件编码...',mode : 'remote',queryParam :'queryParam',
		    queryDelay:500,minChars :2,pageSize:10,listWidth:270,store : ds_code_select,
		    selectOnFocus : true,editable : true,triggerAction : 'all',loadingText : '加载中...'
		};		
		config=Ext.apply(defaultConfig,config||{});
		var combo=new Ext.form.ComboBox(config);
		return combo;
	},
	
	getPartnerCombo:function(config,relationType){
		var partnerStore = new Ext.data.JsonStore({
			url : Uec3.App.Constants.homeUrl+ "/partner/query_partner!queryPartner.do",
			root : 'root',totalProperty : 'totalProperty',remoteSort : true,
			baseParams : {start : 0,limit : 6,type : relationType},
			fields : [{name : 'id',type : 'int'},{name : 'pyCode',type : 'string'},{name : 'name',type : 'string'},{name : 'companyId',type : 'int'}]});	
		var defaultConfig={store: partnerStore,fieldLabel : relationType == 0 ? '客户':'供货单位', displayField:'name',
	        lookupField:'pyCode',valueField:'id',
	        hiddenId : relationType == 0 ?'partnerIdBySeller_' + new Date().getTime():'partnerIdByBuyer_'+new Date().getTime(),
	        hiddenName : relationType == 0 ?'partnerIdBySeller' : 'partnerIdByBuyer',
	        typeAhead: false,mode: 'remote',triggerAction: 'all', emptyText:relationType == 0 ? '选择客户...' : '选择供货商..',	       
	        selectOnFocus:true,queryParam:'queryParam',queryDelay:10,typeAheadDelay:10,
	        pageSize:6,start:0,width:250,anchor : '100%',
	        app:Uec3.App,
	        triggerTags : [{moduleId:'partner_query',triggerClass:'x-form-search-trigger',params:{partnerType:relationType}},{moduleId:'partner_add'}],
	        cleanValueTrigger : {triggerHandler : function() {this.readyToClearValue();},triggerClass : 'x-form-clear-trigger'},
			onSelect : function(record, index) {
				if (this.fireEvent('beforeselect', this, record, index) !== false) {
					this.collapse();
					this.fireEvent('select', this, record, index);
				}
			}
		};
		config=Ext.apply(defaultConfig,config||{});
		var combo=new Ext.form.LookupBox2(config);
		return combo;
	}
});    
Uec3.App.fieldFactory=new Uec3.FieldFactory();   